package cn.edu.lcvc.ebuy_2023rj2.web.filter;

import cn.edu.lcvc.ebuy_2023rj2.model.Admin;
import cn.edu.lcvc.ebuy_2023rj2.model.common.ResponseData;
import cn.edu.lcvc.ebuy_2023rj2.service.AdminService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录拦截器
 */
public class LoginForAdminOfJsonInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private AdminService adminService;

    /**
     * 在执行被拦截的controller之前执行。 如果返回true则表示不拦截，返回false表示拦截，即无法访问Controller。
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean result=true;//默认不拦截
        //判断登录状态
        HttpSession session=request.getSession();
        //1.获取当前登录账户信息
        Admin admin=(Admin)session.getAttribute("admin");
        if (admin!=null){//如果已经登录
            if (!adminService.login(admin.getUsername(),admin.getPassword())){//如果密码已经被修改
                session.removeAttribute("admin");
                result=false;//拒绝登录
            }
        }else{//如果没有登录
            result=false;
        }
        if (result==false){//如果被拒绝访问
           response.setContentType("application/json;charset=UTF-8");
           response.getWriter().write(JSON.toJSONString(ResponseData.error(401,"操作失败，请先登录")));
        }
        return result;
    }
}
